/**
 * Created by TKBnice on 21/03/10.
 */
import md5 from "js-md5";
/**
 * 将日期格式化成指定格式的字符串
 * @param date 要格式化的日期，不传时默认当前时间，也可以是一个时间戳
 * @param fmt 目标字符串格式，支持的字符有：y,M,d,q,w,H,h,m,S，默认：yyyy-MM-dd HH:mm:ss
 * @returns 返回格式化后的日期字符串
 */
export function formatDate(date, fmt) {
  date = date === undefined ? new Date() : date;
  date = typeof date === "number" ? new Date(date) : date;
  fmt = fmt || "yyyy-MM-dd HH:mm:ss";
  var obj = {
    y: date.getFullYear(), // 年份，注意必须用getFullYear
    M: date.getMonth() + 1, // 月份，注意是从0-11
    d: date.getDate(), // 日期
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    w: date.getDay(), // 星期，注意是0-6
    H: date.getHours(), // 24小时制
    h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
    m: date.getMinutes(), // 分钟
    s: date.getSeconds(), // 秒
    S: date.getMilliseconds(), // 毫秒
  };
  var week = ["天", "一", "二", "三", "四", "五", "六"];
  for (var i in obj) {
    fmt = fmt.replace(new RegExp(i + "+", "g"), function(m) {
      var val = obj[i] + "";
      if (i === "w") return (m.length > 2 ? "星期" : "周") + week[val];
      for (var j = 0, len = val.length; j < m.length - len; j++) {
        val = "0" + val;
      }
      return m.length === 1 ? val : val.substring(val.length - m.length);
    });
  }
  return fmt;
}

/**
 * @description 深度克隆
 * @param {string} source
 * @returns {Object}
 */
export const deepCopy = (source) => {
  var sourceCopy = source instanceof Array ? [] : {};
  for (var item in source) {
    sourceCopy[item] =
      typeof source[item] === "object" ? deepCopy(source[item]) : source[item];
  }
  return sourceCopy;
};

/**
 * @description 合并
 * @param {string} target
 * @param {string} source
 * @returns {Object}
 */
function merge(target, source) {
  while (source.length > 0) {
    target.push(source.pop());
  }
}

/**
 * 生成树形结构
 * @param  datas 数组
 * @param parentId 父节点
 * @returns 树形结构
 */
export function getTree(datas, parentId) {
  const dataMap = {};
  const dataTree = {};
  while (datas.length > 0) {
    const data = datas.pop();
    if (!data.submenu) {
      data.submenu = [];
    }
    if (data.parentId === parentId) {
      dataTree[data.menuId] = data;
    } else {
      if (dataMap[data.parentId]) {
        const submenu = dataMap[data.parentId].submenu;
        submenu.push(data);
      } else {
        dataMap[data.parentId] = {
          submenu: [data],
        };
      }
    }
    if (data.submenu) {
      merge(datas, data.submenu);
    }
    if (dataMap[data.menuId]) {
      merge(data.submenu, dataMap[data.menuId].submenu);
    }
    dataMap[data.menuId] = data;
  }
  return dataTree;
}

/**
 * 下载excel
 * @param  data  接口返回数据 res.data
 * @param res 接口返回数据 res
 * @returns excel文件
 */
export function exportExcel(data, res) {
  if (!data) {
    // 如果没有data数据就不进行操作
    return;
  }

  // 获取headers中的filename文件名
  var tempName = res.data.data.headers["Content-Disposition"]
    .split(";")[1]
    .split("filename=")[1];

  // iconv-lite解决中文乱码
  const iconv = require("iconv-lite");
  iconv.skipDecodeWarning = true; // 忽略警告
  const fileName = iconv.decode(tempName, "gbk");
  const blob = new Blob([data], { type: "application/vnd.ms-excel" }); // 转换成二进制对象
  if ("download" in document.createElement("a")) {
    // 不是IE浏览器
    const url = window.URL.createObjectURL(blob); // 二进制对象转换成url地址
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); // 下载完成移除元素
    window.URL.revokeObjectURL(url); // 释放掉blob对象
  } else {
    window.navigator.msSaveBlob(blob, fileName);
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function(...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @description 格式化上传文件名称
 * @param {*} name
 * @returns 文件名_日期.后缀
 */
export function packFileName(name) {
  if (!name) {
    console.log("require at least one parameter is needed");
    return;
  }
  const point = name.lastIndexOf(".");
  const suffix = name.substr(point);
  const fileName = name.substr(0, point);
  const date = formatDate(new Date(), "yyyyMMddHHmm");
  const OSSfileName = `${fileName}_${date}${suffix}`;
  return OSSfileName;
}

/**
 * @description 计算日期之间的月数,要求日期格式：2019-3-12
 * @param date1 要求日期格式：2019-3-12
 * @param date1 要求日期格式：2019-3-12
 * @returns月份差
 */
//
export function calcMonthDiff(startDate, endDate) {
  // 拆分年月日
  startDate = startDate.split("-");
  // 得到月数
  startDate = parseInt(startDate[0]) * 12 + parseInt(startDate[1]);
  // 拆分年月日
  endDate = endDate.split("-");
  // 得到月数
  endDate = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);
  var monthDiff = Math.abs(startDate - endDate);
  return monthDiff;
}
/**
 * @description 计算2个日期相差的天数，不包含今天，如：2016-12-13到2016-12-15，相差2天
 * @param startDateString
 * @param endDateString
 * @returns
 */
export function dateDiff(startDateString, endDateString) {
  var separator = "-"; // 日期分隔符
  var startDates = startDateString.split(separator);
  var endDates = endDateString.split(separator);
  var startDate = new Date(startDates[0], startDates[1] - 1, startDates[2]);
  var endDate = new Date(endDates[0], endDates[1] - 1, endDates[2]);
  return parseInt(Math.abs(endDate - startDate) / 1000 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
}

/**
 * @description 计算2个日期相差的天数，包含今天，如：2016-12-13到2016-12-15，相差3天
 * @param startDateString
 * @param endDateString
 * @returns
 */
export function dateDiffIncludeToday(startDateString, endDateString) {
  var separator = "-"; // 日期分隔符
  var startDates = startDateString.split(separator);
  var endDates = endDateString.split(separator);
  var startDate = new Date(startDates[0], startDates[1] - 1, startDates[2]);
  var endDate = new Date(endDates[0], endDates[1] - 1, endDates[2]);
  return parseInt(Math.abs(endDate - startDate) / 1000 / 60 / 60 / 24) + 1; // 把相差的毫秒数转换为天数
}

/**
 * @description 根据cookieName获取cookie内容
 * @param cookieName cookie名称
 */
export function getCookie(cookieName) {
  if (document.cookie.length > 0) {
    let cStart = document.cookie.indexOf(cookieName + "=");
    if (cStart !== -1) {
      cStart = cStart + cookieName.length + 1;
      let cEnd = document.cookie.indexOf(";", cStart);
      if (cEnd === -1) cEnd = document.cookie.length;
      return unescape(document.cookie.substring(cStart, cEnd));
    }
  }
  return "";
}

/**
 * @description 根据json生成待打印表格的html
 * @param jsonData 待打印的json数组
 * @param properties 需要打印的字段key
 * @param aliases 表头字段值
 */
export function jsonToHTML(jsonData, properties, aliases) {
  const data = jsonData;
  let htmlData = '<div style="display:flex; flex-direction: column;">';

  // Header
  htmlData += '<div style="flex:1 1 auto; display:flex;">';

  for (let a = 0; a < properties.length; a++) {
    htmlData +=
      '<div style="flex:1; padding:5px;font-weight: bold;border: 1px solid lightgray; margin-bottom: -1px;">' +
      aliases[a] +
      "</div>";
  }

  htmlData += "</div>";

  // Data
  for (let i = 0; i < data.length; i++) {
    htmlData += '<div style="flex:1 1 auto; display:flex;">';

    // Print selected properties only
    for (let n = 0; n < properties.length; n++) {
      let stringData = data[i];

      // Support for nested objects
      const property = properties[n].split(".");
      if (property.length > 1) {
        for (let p = 0; p < property.length; p++) {
          stringData =
            stringData[property[p]] === undefined
              ? ""
              : stringData[property[p]];
        }
      } else {
        stringData =
          stringData[properties[n]] === undefined
            ? ""
            : stringData[properties[n]];
      }

      htmlData +=
        '<div style="flex:1; padding:5px;border: 1px solid lightgray; margin-bottom: -1px;">' +
        stringData +
        "</div>";
    }

    htmlData += "</div>";
  }

  htmlData += "</div>";
  return htmlData;
}

/**
 * @description 数字转换为软妹币
 * @param n 数字
 * @param aliases 表头字段值
 */
export function number2Chinese(n) {
  if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
    return "数据非法";
  }
  let unit = "千百拾亿千百拾万千百拾元角分";
  let str = "";
  n += "00";
  const p = n.indexOf(".");
  if (p >= 0) {
    n = n.substring(0, p) + n.substr(p + 1, 2);
  }
  unit = unit.substr(unit.length - n.length, unit.length);
  for (let i = 0; i < n.length; i++) {
    str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);
  }
  return str
    .replace(/零(千|百|拾|角)/g, "零")
    .replace(/(零)+/g, "零")
    .replace(/零(万|亿|元)/g, "$1")
    .replace(/(亿)万|壹(拾)/g, "$1$2")
    .replace(/^元零?|零分/g, "")
    .replace(/元$/g, "元整");
}

/**
 * @description 根据条件查询表格
 */
export function putValueIntoCondition(
  conditions,
  searchForm,
  name,
  defaultValue,
  isRange,
  startName,
  endName
) {
  const value = searchForm[name];
  if (value || (value !== "" && value !== null && value !== undefined)) {
    if (value instanceof Array) {
      if (value.length > 0) {
        if (isRange) {
          if (startName) {
            conditions.push({
              condType: startName,
              condValue: [value[0]],
            });
          }
          if (endName) {
            conditions.push({
              condType: endName,
              condValue: [value[1]],
            });
          }
        } else {
          conditions.push({
            condType: name,
            condValue: value,
          });
        }
      }
    } else {
      conditions.push({
        condType: name,
        condValue: [value],
      });
    }
  } else {
    if (
      defaultValue ||
      (value !== "" && value !== null && value !== undefined)
    ) {
      if (defaultValue instanceof Array) {
        if (defaultValue.length > 0) {
          if (isRange) {
            if (startName) {
              conditions.push({
                condType: startName,
                condValue: [defaultValue[0]],
              });
            }
            if (endName) {
              conditions.push({
                condType: endName,
                condValue: [defaultValue[1]],
              });
            }
          } else {
            conditions.push({
              condType: name,
              condValue: defaultValue,
            });
          }
        }
      } else {
        conditions.push({
          condType: name,
          condValue: [defaultValue],
        });
      }
    }
  }
}

/**
 * @description 获取树形值
 */
export function getTreeValue(treeData, value, fieldName) {
  for (const data of treeData) {
    if (data[fieldName] === value) {
      return data;
    }
    if (data.children) {
      const result = getTreeValue(data.children, value, fieldName);
      if (result) return result;
    }
  }
}

/**
 * @description 根据key获取可迭代list中的value
 */
export function getValueByIdInList(id, list, idKeyName, valueKeyName) {
  const item = list.find((eachOne) => {
    return eachOne[idKeyName] === id;
  });
  if (item) return item[valueKeyName];
  else return "";
}
